'use strict';

const semver = require('semver')
const axios = require('axios')
const urlJoin = require('url-join')

const ORIGINAL_REGISTRY = 'https://registry.npmjs.org'
const TAO_BAO_REGISTRY = 'https://registry.npm.taobao.org'

function getDefaultRegistry() {
    let isOriginal
    if (process.env.USE_TAO_BAO && process.env.USE_TAO_BAO.toLowerCase() === 'false') {
        isOriginal = true
    } else isOriginal = !(process.env.USE_TAO_BAO && process.env.USE_TAO_BAO.toLowerCase() === 'true');
    return isOriginal ? ORIGINAL_REGISTRY : TAO_BAO_REGISTRY
}

function getNpmInfo(npmName, registry) {
    if (!npmName) {
        throw new Error('npm name is null!')
    }
    const registryUrl = registry || getDefaultRegistry()
    const npmInfoUrl = urlJoin(registryUrl, npmName)
    return axios.get(npmInfoUrl).then(response => {
        if (response.status === 200) {
            return response.data
        }
    }).catch(err => {
        return Promise.reject(err)
    })
}

async function getNpmVersions(npmName, registry) {
    const data = await getNpmInfo(npmName, registry)
    return Object.keys(data.versions);
}

async function getSemverVersions(basePkgVersion, npmName, registry) {
    return (await getNpmVersions(npmName, registry))
        .filter(v => semver.lt(basePkgVersion, v))
        .sort((a, b) => {
            if (semver.gt(a, b)) {
                return -1
            } else {
                return 1
            }
        })
}

async function getSemverVersion(basePkgVersion, npmName, registry) {
    const semverVersions = await getSemverVersions(...arguments)
    if (semverVersions && semverVersions.length) {
        return semverVersions[0]
    }
}

async function getLatestVersion(npmName, registry) {
    const versions = (await getNpmVersions(npmName, registry))
        .sort((a, b) => {
            if (semver.gt(a, b)) {
                return -1
            } else {
                return 1
            }
        })
    return versions[0]
}

module.exports = {
    getSemverVersion,
    getDefaultRegistry,
    getLatestVersion
};
